/**
 * Created by PanJiaChen on 16/11/18.
 */

import axios from 'axios'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export const delay = (function() {
  let timer = 0
  return function(callback, ms) {
    clearTimeout(timer)
    timer = setTimeout(callback, ms)
  }
})()

/**
 * 扁平化转tree
 * @param items 要转换的数组{必须包含有id，pid参数} 例： [{id:1, pid:0, text: '张三'}, ...]
 * @param option 子节点默认放在children属性中，可自定义子节点名称
 * @returns {*[]} 返回转换之后得到数组
 */
export function arrayToTree(items, option = { children: 'children' }) {
  const result = [] // 存放结果集
  const itemMap = {} //
  for (const item of items) {
    const id = item.id
    const pid = item.pid || 0

    if (!itemMap[id]) {
      itemMap[id] = {
        [option.children]: []
      }
    }

    itemMap[id] = {
      [option.children]: itemMap[id][[option.children]],
      ...item
    }

    const treeItem = itemMap[id]

    if (pid === 0) {
      result.push(treeItem)
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          [option.children]: []
        }
      }
      itemMap[pid][option.children].push(treeItem)
    }
  }
  // 遍历如果最后没有匹配到pid为0的就放到第一列(todo 后续可能需要优化这里)
  for (const key in itemMap) {
    if (!itemMap[key]['id']) {
      itemMap[key][option.children] && result.push(itemMap[key][option.children][0])
    }
  }
  return result
}

/**
 * 递归查询（根据id查询到某一项）
 * @param id 要查询的id
 * @param list 要遍历的数组 必须包含id 例：[{ id: 1, text: '张三' }]
 * @param opt 子节点数据，默认children，可自定义子节点名称
 * @returns {null} 返回当前查询到的结果
 */
export function treeFind(id, list = [], opt) {
  const options = {
    id: 'id',
    children: 'children',
    ...opt
  }

  let data = null
  list.map(item => {
    if (item[options.id] === id) {
      data = item
    } else {
      const obj = treeFind(id, item[options.children], options)
      if (obj) {
        data = obj
      }
    }
  })
  return data
}
/**
 * 递归查询（根据id查询到符合条件全部项）
 * @param id 要查询的id
 * @param list 要遍历的数组 必须包含id 例：[{ id: 1, text: '张三' }]
 * @param options 子节点数据，默认children，可自定义子节点名称
 * @returns {null} 返回当前查询到的结果
 */
export function treeFindAll(id, list = [], options = { children: 'children' }, items = []) {
  list.map(item => {
    if (item.id === id) {
      items.push(item)
    } else {
      const obj = treeFind(id, item[options.children], options)
      if (obj) {
        items = [...items, obj]
      }
    }
  })
  return items
}

/**
 * 递归删除（根据id删除某一项）返回一个新数组
 * @param id 要删除的id
 * @param list 要遍历的数组 必须包含id 例：[{ id: 1, text: '张三' }]
 * @returns {*[]|*} 数组
 */
export function treeFindDel(id, list) {
  if (typeof list !== 'object' || list === null) {
    return list
  }
  const newList = Array.isArray(list) ? [] : {}
  Object.keys(list).forEach(key => {
    if (id !== list[key].id) {
      newList[key] = treeFindDel(id, list[key])
    }
  })
  return newList
}

// 转换首字母为大写
export function titleCase(str) {
// 把字符串根据空格转换成字符数组
  var arr = str.split(' ')
  // 遍历字符数组
  for (var i = 0; i < arr.length; i++) {
    // 把第一个字符变为大写,其余字符变为小写
    arr[i] = arr[i].slice(0, 1).toUpperCase() + arr[i].slice(1)
  }
  // 加上空格，返回原模式的字符串
  return arr.join(' ')
}

/**
 * 下载链接文件
 * @param url 文件网址
 * @param name 自定义文件名称（需要传递后缀名称）
 */
export function downloadByURL(url, name) {
  if (!name) { // 如果没有提供名字，从给的Link中截取的文件名称
    name = url.slice(url.lastIndexOf('/') + 1)
  }
  axios.request({
    url: url,
    responseType: 'blob'
  }).then((res) => {
    const link = URL.createObjectURL(res.data)
    const eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
  })
}
export const machineIcon = {
  windows: 'Windows',
  linux: 'linux',
  unix: 'Unix',
  aix: 'Aix',
  as400: 'AS400',
  交换机: 'jiaohuanji',
  路由器: 'luyouqi',
  防火墙: 'fanghuoqiang',
  负载均衡: 'fuzaijunheng',
  存储设备: 'a-94_cunchushebei'
}
export function formatSeconds(value) { // 秒数转换为 时分秒
  const result = parseInt(value)
  const h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600)
  const m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60))
  const s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60))

  let res = ''
  res += `${h}:`
  res += `${m}:`
  res += `${s}`
  return res
}
// 根据环境拼接文件地址
export const fileHostUrl = (process.env.NODE_ENV === 'development' ? process.env.VUE_APP_LOCOL_HOST : '')
